package com.sdstc.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruoyi.common.base.BaseServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.enums.*;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDictTypeService;
import com.sdstc.modules.dao.OrgDao;
import com.sdstc.modules.dao.PersonDao;
import com.sdstc.modules.dto.PersonExcelDto;
import com.sdstc.modules.dto.PersonExcelNewDto;
import com.sdstc.modules.eneity.*;
import com.sdstc.modules.service.ImportErrorService;
import com.sdstc.modules.service.OrgService;
import com.sdstc.modules.service.PersonService;
import com.sdstc.modules.uitl.ExcelUtils;
import com.sdstc.modules.uitl.TreeUtils;
import com.sdstc.modules.vo.OrgDetailVo;
import com.sdstc.modules.vo.OrgTreeVo;
import com.sdstc.modules.vo.ScreenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author ：wk
 * @date ：Created in 2022/10/23 13:26
 */
@Service
public class PersonServiceImpl extends BaseServiceImpl<PersonDao,PersonEntity> implements PersonService {

    @Autowired
    private PersonDao personDao;

    @Autowired
    private OrgDao orgDao;

    @Autowired
    private OrgService orgService;

    @Autowired
    private ImportErrorService importErrorService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    private final String orgLeader = "部门领导";

    private final String branchLeaders = "分局领导";

    private final String jobLevelDict[] = {"law_enforcement", "general_management", "police_skills"};

    private final String personStatusDict = "person_status";

    @Override
    public PersonEntity savePerson(PersonEntity person) {
        personDao.insert(person);
        return person;
    }

    @Override
    public PersonEntity updatePerson(PersonEntity person) {
        personDao.updateById(person);
        return person;
    }

    @Override
    public void deletePersonById(String id) {
        personDao.deleteById(id);
    }

    @Override
    public List<PersonEntity> getPersonPage(PersonEntity person, List<SysDictData> jobLevelDictData, Map<String, OrgTreeVo> orgId2Map){

        List<PersonEntity> personEntityList;

        if (Objects.nonNull(person.getStartAge()) || Objects.nonNull(person.getEndAge())) {

            int endYear = Objects.nonNull(person.getStartAge()) ?
                    LocalDate.now().minusYears(person.getStartAge()).getYear() : LocalDate.now().getYear();
            int startYear = Objects.nonNull(person.getEndAge()) ?
                    LocalDate.now().minusYears(person.getEndAge()).getYear() : LocalDate.now().minusYears(200).getYear();

            int month = LocalDate.now().getMonth().getValue();
            int day = LocalDate.now().getDayOfMonth();

            String endYearStr = endYear + "" + month + (day < 10 ? "0" + day : day);
            String startYearStr = startYear + "" + month + (day < 10 ? "0" + day : day);

            personEntityList = personDao.selectList(new QueryWrapper<PersonEntity>()
                    .in(CollectionUtils.isNotEmpty(orgId2Map), "org_id", orgId2Map.keySet())
                    .like(StringUtils.isNotBlank(person.getName()), "name", person.getName())
                    .like(StringUtils.isNotBlank(person.getIdentityNo()), "identity_no", person.getIdentityNo())
                    .eq(StringUtils.isNotBlank(person.getStatus()), "status", person.getStatus())
                    .eq(StringUtils.isNotBlank(person.getSex()), "sex", person.getSex())
                    .like(StringUtils.isNotBlank(person.getEducation()), "education", person.getEducation())
                    .in(StringUtils.isNotBlank(person.getLeaderType()), "leader_type", person.getLeaderType())
                    .ge("substring( identity_no, 7, 8 )", startYearStr).le("substring( identity_no, 7, 8 )", endYearStr)
                    .orderByAsc("org_id"));

        }else {
            personEntityList = personDao.selectList(new QueryWrapper<PersonEntity>()
                    .in(CollectionUtils.isNotEmpty(orgId2Map), "org_id", orgId2Map.keySet())
                    .like(StringUtils.isNotBlank(person.getName()), "name", person.getName())
                    .like(StringUtils.isNotBlank(person.getIdentityNo()), "identity_no", person.getIdentityNo())
                    .eq(StringUtils.isNotBlank(person.getStatus()), "status", person.getStatus())
                    .eq(StringUtils.isNotBlank(person.getSex()), "sex", person.getSex())
                    .like(StringUtils.isNotBlank(person.getEducation()), "education", person.getEducation())
                    .in(StringUtils.isNotBlank(person.getLeaderType()), "leader_type", person.getLeaderType())
                    .orderByAsc("org_id"));
        }

        Map<String, String> value2Label = jobLevelDictData.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (PersonEntity personEntity : personEntityList) {
            String jobLevelSmall = personEntity.getJobLevelSmall();
            if (StringUtils.isNotBlank(jobLevelSmall)){
                personEntity.setJobLevelSmallLabel(StringUtils.isNotBlank(value2Label.get(jobLevelSmall)) ? value2Label.get(jobLevelSmall) : "");
            }
            personEntity.setOrgName(orgId2Map.get(personEntity.getOrgId()).getOrgName());
        }
        return personEntityList;
    }

    @Override
    public void importPersonByExcel(HttpServletResponse response, MultipartFile file, String orgId) throws IOException {


        // 要导入的数据
        List<PersonExcelDto> personExcelDtoList = ExcelUtils.importExcel(file, PersonExcelDto.class);

        if (CollectionUtils.isEmpty(personExcelDtoList)){
            throw new RuntimeException("导入文件为空");
        }

        importErrorService.remove(new QueryWrapper<>());

        Map<String, PersonExcelDto> originData = personExcelDtoList.stream().collect(Collectors.toMap(p -> builderKey(p.getName(), p.getIdentityNo()), Function.identity()));

        List<OrgEntity> orgEntities = orgDao.selectList(new QueryWrapper<>());

        // 该机构
        OrgEntity orgEntityItself = orgDao.selectById(orgId);

        OrgDetailVo orgDetailVo = new OrgDetailVo();
        orgDetailVo.setOrgName(orgEntityItself.getOrgName());
        orgDetailVo.setOrgLevel(orgEntityItself.getOrgLevel());
        orgDetailVo.setOrgType(orgEntityItself.getOrgType());


        List<OrgTreeVo> orgTreeItselfList = TreeUtils.getAllOrg(orgId, orgEntities);
        orgTreeItselfList.add(OrgTreeVo.getInstance(orgEntityItself));

        // 不包括部门领导、分局领导的集合
        List<OrgTreeVo> orgList = orgTreeItselfList.stream().filter(org -> !Objects.equals(org.getOrgName(), orgLeader) && !Objects.equals(org.getOrgName(), branchLeaders)).collect(Collectors.toList());

        Map<String, OrgTreeVo> org2Map = orgList.stream().collect(Collectors.toMap(OrgTreeVo::getOrgName, Function.identity()));

        // 部门领导、分局领导集合
        List<OrgTreeVo> leaderOrgList = orgTreeItselfList.stream().filter(org -> Objects.equals(org.getOrgName(), orgLeader) || Objects.equals(org.getOrgName(), branchLeaders)).collect(Collectors.toList());

        Map<String, OrgTreeVo> leaderOrg2Map = leaderOrgList.stream().collect(Collectors.toMap(s -> builderKey(s.getPid(), s.getOrgName()), Function.identity()));

        personExcelDtoList = personExcelDtoList.stream().filter(p -> StringUtils.isNotBlank(p.getOrgName())).collect(Collectors.toList());

        // 职级
        List<SysDictData> jobLevelDictItem = new ArrayList<>();
        for (String s : jobLevelDict) {
            jobLevelDictItem.addAll(dictTypeService.selectDictDataByType(s));
        }
        if (CollectionUtils.isEmpty(jobLevelDictItem)){
            return;
        }

        Map<String, SysDictData> jobLevel2Map = jobLevelDictItem.stream().collect(Collectors.toMap(SysDictData::getDictLabel, Function.identity()));

        // 人员状态
        List<SysDictData> personStatusDictItem = dictTypeService.selectDictDataByType(personStatusDict);

        if (CollectionUtils.isEmpty(personStatusDictItem)){
            return;
        }
        Map<String, SysDictData> personStatus2Map = personStatusDictItem.stream().collect(Collectors.toMap(SysDictData::getDictLabel, Function.identity()));

        // 行政
        List<SysDictData> adminDict = dictTypeService.selectDictDataByType(OrganType.ADMIN.getCode());
        Map<String, SysDictData> admin2Map = adminDict.stream().collect(Collectors.toMap(SysDictData::getDictLabel, Function.identity()));
        // 事业
        List<SysDictData> causeDict = dictTypeService.selectDictDataByType(OrganType.CAUSE.getCode());
        Map<String, SysDictData> cause2Map = causeDict.stream().collect(Collectors.toMap(SysDictData::getDictLabel, Function.identity()));
        // 工勤
        List<SysDictData> workDict = dictTypeService.selectDictDataByType(OrganType.WORK.getCode());
        Map<String, SysDictData> work2Map = workDict.stream().collect(Collectors.toMap(SysDictData::getDictLabel, Function.identity()));

        List<PersonEntity> saveList = personExcelDtoList.stream().map(item -> {

            PersonEntity personEntity = new PersonEntity();


            // 姓名
            personEntity.setName(item.getName());
            // 性别
            personEntity.setSex(Objects.requireNonNull(SexType.sexTypeOf(item.getSex())).getCode());
            // 所在部门 -> 人员所在单位
            // 如果当前部门为 部门领导或者分局领导
            if ((Objects.equals(item.getOrgName(), orgLeader) || Objects.equals(item.getOrgName(), branchLeaders)) && StringUtils.isNotBlank(item.getUnitName())
                    && Objects.nonNull(org2Map.get(item.getUnitName())) && StringUtils.isNotBlank(org2Map.get(item.getUnitName()).getId())){
                // 取到部门领导、分局领导的上级
                String leaderOrgPid = org2Map.get(item.getUnitName()).getId();
                if (Objects.nonNull(leaderOrg2Map.get(builderKey(org2Map.get(item.getUnitName()).getId(), orgLeader)))){
                    personEntity.setOrgId(leaderOrg2Map.get(builderKey(leaderOrgPid, orgLeader)).getId());
                }
                if (Objects.nonNull(leaderOrg2Map.get(builderKey(org2Map.get(item.getUnitName()).getId(), branchLeaders)))){
                    personEntity.setOrgId(leaderOrg2Map.get(builderKey(leaderOrgPid, branchLeaders)).getId());
                }
            }

//            if (Objects.equals(item.getOrgName(), orgLeader) && StringUtils.isNotBlank(item.getUnitName())){
//                // 取到部门领导的上级
//                if (Objects.nonNull(org2Map.get(item.getUnitName())) && StringUtils.isNotBlank(org2Map.get(item.getUnitName()).getId()) && Objects.nonNull(leaderOrg2Map.get(builderKey(org2Map.get(item.getUnitName()).getId(), orgLeader)))){
//                    String leaderOrgPid = org2Map.get(item.getUnitName()).getId();
//                    personEntity.setOrgId(leaderOrg2Map.get(builderKey(leaderOrgPid, orgLeader)).getId());
//                }
//            }


            // 当前部门不是部门领导 也不是分局领导
            if (!Objects.equals(item.getOrgName(), orgLeader) && Objects.nonNull(org2Map.get(item.getOrgName()))){
                personEntity.setOrgId(org2Map.get(item.getOrgName()).getId());
            }

            // 人员分类 -> 领导类型
            if (Objects.nonNull(LeaderType.leaderTypeOf(item.getPersonType()))){
                personEntity.setLeaderType(Objects.requireNonNull(LeaderType.leaderTypeOf(item.getPersonType())).getCode());
            }

            // 职务层次 目前分为 机关行政编制 -> 行政、机关工勤编制 -> 工勤、事业编制 -> 事业
            if (StringUtils.isNotBlank(item.getStaffing())){
                if (Objects.equals("机关行政编制", item.getStaffing())){
                    personEntity.setPostBigCateCode(OrganType.ADMIN.getCode());
                    if (StringUtils.isNotBlank(item.getPostType()) && Objects.nonNull(admin2Map.get(item.getPostType()))){
                        personEntity.setPostSmallCateCode(admin2Map.get(item.getPostType()).getDictValue());
                    }
                }
                if (Objects.equals("机关工勤编制", item.getStaffing())){
                    personEntity.setPostBigCateCode(OrganType.WORK.getCode());
                    if (StringUtils.isNotBlank(item.getPostType()) && Objects.nonNull(work2Map.get(item.getPostType()))){
                        personEntity.setPostSmallCateCode(work2Map.get(item.getPostType()).getDictValue());
                    }
                }
                if (Objects.equals("事业编制", item.getStaffing())){
                    personEntity.setPostBigCateCode(OrganType.CAUSE.getCode());
                    if (StringUtils.isNotBlank(item.getPostType()) && Objects.nonNull(cause2Map.get(item.getPostType()))){
                        personEntity.setPostSmallCateCode(cause2Map.get(item.getPostType()).getDictValue());
                    }
                }
            }


            // 职级 -> 职级层次
            if (StringUtils.isNotBlank(item.getJobLevel())){
                SysDictData sysDictData = jobLevel2Map.get(item.getJobLevel());
                if (Objects.nonNull(sysDictData)){
                    personEntity.setJobLevel(sysDictData.getDictType());
                    personEntity.setJobLevelSmall(sysDictData.getDictValue());
                }
            }

            // 职务名称
            personEntity.setPositionTitle(item.getPositionTitle());

            // 身份证号
            personEntity.setIdentityNo(item.getIdentityNo());

            // 学历
            personEntity.setEducation(item.getEducation());

            // 人员状态
            if (StringUtils.isNotBlank(item.getStatus()) && Objects.nonNull(personStatus2Map.get(item.getStatus()))){
                personEntity.setStatus(personStatus2Map.get(item.getStatus()).getDictValue());
            }


            return personEntity;
        }).collect(Collectors.toList());

        // 未导入的数据
        List<ImportErrorEntity> importErrorEntityList = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(saveList)){
            Map<String, PersonEntity> resultData = saveList.stream().collect(Collectors.toMap(s -> builderKey(s.getName(), s.getIdentityNo()), Function.identity()));
            for (String oKey : originData.keySet()) {
                if (Objects.isNull(resultData.get(oKey))){
                    ImportErrorEntity importErrorEntity = new ImportErrorEntity();
                    importErrorEntity.setName(oKey.split("_")[0]);
                    importErrorEntity.setIdentityNo(oKey.split("_")[1]);
                    importErrorEntity.setImportTime(new Date());
                    importErrorEntityList.add(importErrorEntity);
                }
            }
        }

        this.saveBatch(saveList);
        importErrorService.saveBatch(importErrorEntityList);
    }

    /**
    *@author: wk
    *@date: 2023/9/22 15:03
    *@description: 根据新的模板导入
    */
    @Override
    @Transactional
    public void importPersonByNewExcel(HttpServletResponse response, MultipartFile file, String orgId) throws IOException {

        // 要导入的数据
        List<PersonExcelNewDto> personExcelDtoList = ExcelUtils.importExcel(file, PersonExcelNewDto.class);

        if (CollectionUtils.isEmpty(personExcelDtoList)){
            throw new RuntimeException("导入文件为空");
        }

        importErrorService.remove(new QueryWrapper<>());

        List<OrgEntity> orgEntities = orgDao.selectList(new QueryWrapper<>());

        // 该机构
        OrgEntity orgEntityItself = orgDao.selectById(orgId);

        OrgDetailVo orgDetailVo = new OrgDetailVo();
        orgDetailVo.setOrgName(orgEntityItself.getOrgName());
        orgDetailVo.setOrgLevel(orgEntityItself.getOrgLevel());
        orgDetailVo.setOrgType(orgEntityItself.getOrgType());


        List<OrgTreeVo> orgTreeItselfList = TreeUtils.getAllOrg(orgId, orgEntities);
        orgTreeItselfList.add(OrgTreeVo.getInstance(orgEntityItself));

        // 不包括部门领导、分局领导的集合
        List<OrgTreeVo> orgList = orgTreeItselfList.stream().filter(org -> !Objects.equals(org.getOrgName(), orgLeader) && !Objects.equals(org.getOrgName(), branchLeaders)).collect(Collectors.toList());

        Map<String, OrgTreeVo> org2Map = orgList.stream().collect(Collectors.toMap(OrgTreeVo::getOrgName, Function.identity()));

        // 部门领导、分局领导集合
        List<OrgTreeVo> leaderOrgList = orgTreeItselfList.stream().filter(org -> Objects.equals(org.getOrgName(), orgLeader) || Objects.equals(org.getOrgName(), branchLeaders)).collect(Collectors.toList());

        Map<String, OrgTreeVo> leaderOrg2Map = leaderOrgList.stream().collect(Collectors.toMap(s -> builderKey(s.getPid(), s.getOrgName()), Function.identity()));

        personExcelDtoList = personExcelDtoList.stream().filter(p -> StringUtils.isNotBlank(p.getOrgName())).collect(Collectors.toList());

        // 人员状态
        List<SysDictData> personStatusDictItem = dictTypeService.selectDictDataByType(personStatusDict);

        if (CollectionUtils.isEmpty(personStatusDictItem)){
            return;
        }
        Map<String, SysDictData> personStatus2Map = personStatusDictItem.stream().collect(Collectors.toMap(SysDictData::getDictLabel, Function.identity()));

        // 行政
        List<SysDictData> adminDict = dictTypeService.selectDictDataByType(OrganType.ADMIN.getCode());
        Map<String, SysDictData> admin2Map = adminDict.stream().collect(Collectors.toMap(SysDictData::getDictLabel, Function.identity()));
        // 事业
        List<SysDictData> causeDict = dictTypeService.selectDictDataByType(OrganType.CAUSE.getCode());
        Map<String, SysDictData> cause2Map = causeDict.stream().collect(Collectors.toMap(SysDictData::getDictLabel, Function.identity()));
        // 工勤
        List<SysDictData> workDict = dictTypeService.selectDictDataByType(OrganType.WORK.getCode());
        Map<String, SysDictData> work2Map = workDict.stream().collect(Collectors.toMap(SysDictData::getDictLabel, Function.identity()));
        //单列
//        List<SysDictData> singleDict = dictTypeService.selectDictDataByType(OrganType.SINGLE.getCode());
//        Map<String, SysDictData> single2Map = singleDict.stream().collect(Collectors.toMap(SysDictData::getDictLabel, Function.identity()));

        // 职级层次 大类
        List<SysDictData> personLevelBigLevel = dictTypeService.selectDictDataByType("person_level_big_level");
        Map<String, SysDictData> bigLevel2Map = personLevelBigLevel.stream().collect(Collectors.toMap(SysDictData::getDictLabel, Function.identity()));

        // 职级层次 小类
        List<SysDictData> lawEnforcementData = dictTypeService.selectDictDataByType(PersonLevel.LAW.getCode());
        Map<String, SysDictData> lawEnforcement2Map = lawEnforcementData.stream().collect(Collectors.toMap(SysDictData::getDictLabel, Function.identity()));

        List<SysDictData> generalManagementData = dictTypeService.selectDictDataByType(PersonLevel.MANAGEMENT.getCode());
        Map<String, SysDictData> generalManagement2Map = generalManagementData.stream().collect(Collectors.toMap(SysDictData::getDictLabel, Function.identity()));

        List<SysDictData> policeSkillsData = dictTypeService.selectDictDataByType(PersonLevel.SKILLS.getCode());
        Map<String, SysDictData> policeSkills2Map = policeSkillsData.stream().collect(Collectors.toMap(SysDictData::getDictLabel, Function.identity()));

        // 警衔
        List<SysDictData> jobTitleData = dictTypeService.selectDictDataByType("person_title_type");
        Map<String, SysDictData> jobTitle2Map = jobTitleData.stream().collect(Collectors.toMap(SysDictData::getDictLabel, Function.identity()));


        List<PersonEntity> saveList = personExcelDtoList.stream().map(item -> {

            PersonEntity personEntity = new PersonEntity();

            personEntity.setName(item.getName());
            personEntity.setSex(Objects.nonNull(SexType.sexTypeOf(item.getSex())) ? Objects.requireNonNull(SexType.sexTypeOf(item.getSex())).getCode() : "");
            personEntity.setIdentityNo(item.getIdentityNo());

            // 所在部门 -> 人员所在单位
            // 如果当前部门为 部门领导或者分局领导
            if ((Objects.equals(item.getOrgName(), orgLeader) || Objects.equals(item.getOrgName(), branchLeaders)) && StringUtils.isNotBlank(item.getUnitName())
                    && Objects.nonNull(org2Map.get(item.getUnitName())) && StringUtils.isNotBlank(org2Map.get(item.getUnitName()).getId())){
                // 取到部门领导、分局领导的上级
                String leaderOrgPid = org2Map.get(item.getUnitName()).getId();
                if (Objects.nonNull(leaderOrg2Map.get(builderKey(org2Map.get(item.getUnitName()).getId(), orgLeader)))){
                    personEntity.setOrgId(leaderOrg2Map.get(builderKey(leaderOrgPid, orgLeader)).getId());
                }
                if (Objects.nonNull(leaderOrg2Map.get(builderKey(org2Map.get(item.getUnitName()).getId(), branchLeaders)))){
                    personEntity.setOrgId(leaderOrg2Map.get(builderKey(leaderOrgPid, branchLeaders)).getId());
                }
            }

            // 当前部门不是部门领导 也不是分局领导
            if (!Objects.equals(item.getOrgName(), orgLeader) && Objects.nonNull(org2Map.get(item.getOrgName()))){
                personEntity.setOrgId(org2Map.get(item.getOrgName()).getId());
            }
            personEntity.setEducation(item.getEducation());
            personEntity.setPositionTitle(item.getPositionTitle());
            personEntity.setPoliceNo(item.getPoliceNo());
            personEntity.setJobTitle(Objects.nonNull(jobTitle2Map.get(item.getJobTitle())) ? jobTitle2Map.get(item.getJobTitle()).getDictValue() : "");

            if (StringUtils.isNotBlank(item.getPostBigCateCode())){
                if (Objects.equals(OrganType.ADMIN.getInfo(), item.getPostBigCateCode())){
                    personEntity.setPostBigCateCode(OrganType.ADMIN.getCode());
                    if (StringUtils.isNotBlank(item.getPostSmallCateCode()) && Objects.nonNull(admin2Map.get(item.getPostSmallCateCode()))){
                        personEntity.setPostSmallCateCode(admin2Map.get(item.getPostSmallCateCode()).getDictValue());
                    }
                }
                if (Objects.equals(OrganType.WORK.getInfo(), item.getPostBigCateCode())){
                    personEntity.setPostBigCateCode(OrganType.WORK.getCode());
                    if (StringUtils.isNotBlank(item.getPostBigCateCode()) && Objects.nonNull(work2Map.get(item.getPostBigCateCode()))){
                        personEntity.setPostSmallCateCode(work2Map.get(item.getPostBigCateCode()).getDictValue());
                    }
                }
                if (Objects.equals(OrganType.CAUSE.getInfo(), item.getPostBigCateCode())){
                    personEntity.setPostBigCateCode(OrganType.CAUSE.getCode());
                    if (StringUtils.isNotBlank(item.getPostBigCateCode()) && Objects.nonNull(cause2Map.get(item.getPostBigCateCode()))){
                        personEntity.setPostSmallCateCode(cause2Map.get(item.getPostBigCateCode()).getDictValue());
                    }
                }
//                if (Objects.equals(OrganType.SINGLE.getInfo(), item.getPostBigCateCode())){
//                    personEntity.setPostBigCateCode(OrganType.SINGLE.getCode());
//                    if (StringUtils.isNotBlank(item.getPostBigCateCode()) && Objects.nonNull(single2Map.get(item.getPostBigCateCode()))){
//                        personEntity.setPostSmallCateCode(single2Map.get(item.getPostBigCateCode()).getDictValue());
//                    }
//                }
            }

            // 职级 -> 职级层次
            if (StringUtils.isNotBlank(item.getJobLevel())){
                SysDictData sysDictData = bigLevel2Map.get(item.getJobLevel());
                personEntity.setJobLevel(sysDictData.getDictValue());
                if (StringUtils.isNotBlank(item.getJobLevelSmall())) {
                    if (Objects.equals(sysDictData.getDictValue(), PersonLevel.LAW.getCode())) {
                        personEntity.setJobLevelSmall(lawEnforcement2Map.get(item.getJobLevelSmall()).getDictValue());
                    }
                    if (Objects.equals(sysDictData.getDictValue(), PersonLevel.MANAGEMENT.getCode())) {
                        personEntity.setJobLevelSmall(generalManagement2Map.get(item.getJobLevelSmall()).getDictValue());
                    }
                    if (Objects.equals(sysDictData.getDictValue(), PersonLevel.SKILLS.getCode())) {
                        personEntity.setJobLevelSmall(policeSkills2Map.get(item.getJobLevelSmall()).getDictValue());
                    }
                }
            }

            // 人员分类 -> 领导类型
            if (Objects.nonNull(LeaderType.leaderTypeOf(item.getLeaderType()))){
                personEntity.setLeaderType(Objects.requireNonNull(LeaderType.leaderTypeOf(item.getLeaderType())).getCode());
            }

            // 联系方式
            personEntity.setContactPhone(item.getContactPhone());

            // 人员状态
            if (StringUtils.isNotBlank(item.getStatus()) && Objects.nonNull(personStatus2Map.get(item.getStatus()))){
                personEntity.setStatus(personStatus2Map.get(item.getStatus()).getDictValue());
            }

            return personEntity;
        }).collect(Collectors.toList());

        List<String> identityNoList = saveList.stream().map(PersonEntity::getIdentityNo).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());

        // 根据身份证号更新
        if (CollectionUtils.isNotEmpty(identityNoList)) {
            this.remove(new QueryWrapper<PersonEntity>().in("identity_no", identityNoList));
        }

        this.saveBatch(saveList);
    }

    private static String builderKey(String o1, String o2){
        return o1 + "_" + o2;
    }


    @Override
    public HashMap<String, Object> getEducationChart() {

        // 济南市公安局id
        String orgId = orgService.getJNOrg().get("orgId");
        List<OrgEntity> allOrg = orgDao.selectList(new QueryWrapper<>());
        // 获取改机构下面的所有的机构
        List<OrgTreeVo> orgList = TreeUtils.getAllOrgScreen(orgId, allOrg);

        List<String> orgIdList = orgList.stream().map(OrgTreeVo::getId).collect(Collectors.toList());

        List<String> nameList = Arrays.asList("中专及以下", "大专", "大学", "硕士", "博士");
        List<Long> countList = new ArrayList<>(nameList.size());
        List<PersonEntity> personList = personDao.selectList(new QueryWrapper<PersonEntity>().in("status", Arrays.asList(PersonStatus.OK.getCode(),PersonStatus.HIGH.getCode())).in("org_Id", orgIdList));
        for (String name : nameList) {
            if ("硕士".equals(name)) {
                countList.add(personList.stream().filter(p -> StringUtils.isNotBlank(p.getEducation()) &&
                        (p.getEducation().contains(name) || (p.getEducation().contains("研究生") && !p.getEducation().contains("博士")))).count());
            } else if ("中专及以下".equals(name)) {
                countList.add(personList.stream().filter(p -> (StringUtils.isBlank(p.getEducation()))
                        || (StringUtils.isNotBlank(p.getEducation())
                        && (p.getEducation().contains("第二学士学位班") || p.getEducation().contains("技工学校") || p.getEducation().contains("中等专科") || p.getEducation().contains("小学") || p.getEducation().contains("初中") || p.getEducation().contains("高中") || p.getEducation().contains("中专")))).count());
            } else {
                countList.add(personList.stream().filter(p -> StringUtils.isNotBlank(p.getEducation()) &&
                        p.getEducation().contains(name)).count());
            }

        }

        HashMap<String, Object> result = new HashMap<>();
        result.put("educationName", nameList);
        result.put("educationCount", countList);
        return result;

    }

    @Override
    public void exportEducationExcel(HttpServletResponse response) {

        List<EducationExcelEntity> excelList = new ArrayList<>();

        HashMap<String, Object> educationChart = getEducationChart();
        List<String> educationName = (List<String>) educationChart.get("educationName");
        List<Long> educationCount = (List<Long>) educationChart.get("educationCount");
        for (int i = 0; i < educationName.size(); i++) {
            EducationExcelEntity educationExcelEntity = new EducationExcelEntity();
            educationExcelEntity.setEducationName(educationName.get(i));
            educationExcelEntity.setCount(educationCount.get(i));
            excelList.add(educationExcelEntity);
        }
        ExcelUtil<EducationExcelEntity> util = new ExcelUtil<>(EducationExcelEntity.class);
        util.exportExcel(response, excelList, "学历统计图","学历统计图");
    }

    @Override
    public HashMap<String, Object> getAgeChart() {

        // 济南市公安局id
        String orgId = orgService.getJNOrg().get("orgId");
        List<OrgEntity> allOrg = orgDao.selectList(new QueryWrapper<>());
        // 获取改机构下面的所有的机构
        List<OrgTreeVo> orgList = TreeUtils.getAllOrgScreen(orgId, allOrg);

        List<String> orgIdList = orgList.stream().map(OrgTreeVo::getId).collect(Collectors.toList());

        HashMap<String, Object> result = new HashMap<>();

        List<String> sexNameList = Arrays.asList(SexType.man.getInfo(), SexType.woman.getInfo());

        List<PersonEntity> personList = personDao.selectList(new QueryWrapper<PersonEntity>()
                .in("status", Arrays.asList(PersonStatus.OK.getCode(),PersonStatus.HIGH.getCode()))
                .isNotNull("sex")
                .isNotNull("identity_no")
                .in("org_id", orgIdList)
        );
        List<String> ageNameList = Arrays.asList("25岁及以下", "26-30", "31-35", "36-40", "41-45", "46-50", "51-55", "56岁以上");
        Map<String, Map<String, Long>> ageCountMap = personList.stream()
                .collect(Collectors.groupingBy(PersonEntity::getAgeRange, Collectors.groupingBy(PersonEntity::getSex, Collectors.counting())));
        // 年龄的总数
        List<Long> ageCountList = new ArrayList<>();
        // 男性人数
        List<Long> manCountList = new ArrayList<>();
        // 女性人数
        List<Long> womanCountList = new ArrayList<>();

        for (String ageName : ageNameList) {
            Map<String, Long> sexMap = ageCountMap.getOrDefault(ageName, new HashMap<>());
            Long manCount = sexMap.getOrDefault(SexType.man.getCode(), 0L);
            Long womanCount = sexMap.getOrDefault(SexType.woman.getCode(), 0L);
            manCountList.add(manCount);
            womanCountList.add(womanCount);
            ageCountList.add(manCount + womanCount);
        }

        result.put("ageNameList", ageNameList);
        result.put("sexNameList", sexNameList);
        result.put("ageCountList", ageCountList);
        result.put("manCountList", manCountList);
        result.put("womanCountList", womanCountList);

        return result;
    }

    @Override
    public void exportAgeExcel(HttpServletResponse response) {

        List<AgeExcelEntity> excelList = new ArrayList<>();

        HashMap<String, Object> educationChart = getAgeChart();
        List<String> ageNameList = (List<String>) educationChart.get("ageNameList");
        List<Integer> ageCountList = (List<Integer>) educationChart.get("ageCountList");
        List<Long> manCountList = (List<Long>) educationChart.get("manCountList");
        List<Long> womanCountList = (List<Long>) educationChart.get("womanCountList");
        for (int i = 0; i < ageNameList.size(); i++) {
            AgeExcelEntity ageExcelEntity = new AgeExcelEntity();
            ageExcelEntity.setAge(ageNameList.get(i));
            ageExcelEntity.setMan(manCountList.get(i));
            ageExcelEntity.setWoman(womanCountList.get(i));
            ageExcelEntity.setTotalCount(ageCountList.get(i));
            excelList.add(ageExcelEntity);
        }
        ExcelUtil<AgeExcelEntity> util = new ExcelUtil<>(AgeExcelEntity.class);
        util.exportExcel(response, excelList, "年龄分布统计图","年龄分布统计图");
    }
}
